<template>
  <div class="alanalysis">
    <div class="alanalysis-bridge">
      <CardContainer headerName="倾角分析">
        <!--        Yu 选择桥梁这一块逻辑有点不是通！！ 注销掉-->
        <!--        <template slot="header-right">-->
        <!--          <div class="search">-->
        <!--            <el-button class="seletBtn top" size="small" type="success" icon="el-icon-circle-plus-outline"-->
        <!--                       @click="selectBridge">选择桥梁</el-button>-->
        <!--            <el-tabs class="top" v-model="editableTabsValue" type="card" closable @tab-remove="removeTab">-->
        <!--              <el-tab-pane size="small" :key="item.id" v-for="(item, index) in editableTabs" :label="item.name"-->
        <!--                           :name="item.id"></el-tab-pane>-->
        <!--            </el-tabs>-->
        <!--          </div>-->
        <!--        </template>-->
        <template slot="card-content">
          <div class="alanalysis-bridge-card">
            <div>
              <point :bridgeId="bridgeId" :type="type" @child-event="getPoint"></point>
            </div>
          </div>
        </template>
      </CardContainer>
    </div>

    <div class="alanalysis-chart">
      <div class="alanalysis-chart-time">
        <el-date-picker
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00']"
          style="width: 100%"
          v-model="chartTime"
          type="datetimerange"
          size="small"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          @change="handleChange"
        >
        </el-date-picker>
      </div>
      <div class="alanalysis-chart-box">
        <p class="alanalysis-chart-info">
          倾角最大值：{{ max }}/rad‰、最小值：{{ min }}/rad‰
          <el-checkbox label="阈值" v-model="checked" style="margin-left: 20px"></el-checkbox>
        </p>
        <div class="alanalysis-chart-all" id="stressLine"></div>
      </div>
    </div>

    <SelectBridge ref="selectBridge" @getData="getData"></SelectBridge>
  </div>
</template>

<script>
import CardContainer from '@/views/healthMonitor/components/CardContainer'
import echarts from 'echarts'
import point from './components/point'
import SelectBridge from '@/views/healthMonitor/components/SelectBridge'
import moment from 'moment'
import { mapState, mapMutations } from 'vuex'
export default {
  data() {
    return {
      type: 'QJ',
      line: null,
      chartTime: '',
      bridgeId: '',
      editableTabs: [],
      editableTabsValue: '',
      max: 0,
      min: 0,
      sensorCode: '',
      markLine: [],
      id: '',
      checked: false,
    }
  },
  components: {
    CardContainer,
    SelectBridge,
    point,
  },
  computed: {
    ...mapState('angle', {
      bridgeId: 'bridgeId',
    }),
  },
  watch: {
    bridgeId: {
      handler(newName, oldName) {
        //变化数据
        this.sensorCode = ''
        this.min = 0
        this.max = 0

        if (this.line) {
          this.line.clear()
          this.line.dispose()
        }
        this.$nextTick(() => {
          this.drawLine([])
        })
      },
      immediate: true,
    },
    checked: {
      handler(newVal) {
        if (newVal) {
          //console.log("aaa")
          this.markLine = []
          this.getLine()
          this.getAngleNum(this.sensorCode)
          this.getAngleLineData(this.sensorCode)
        } else {
          this.markLine = []
          this.getAngleNum(this.sensorCode)
          this.getAngleLineData(this.sensorCode)
        }
      },
    },
    editableTabsValue: {
      handler(newVal) {
        this.setBridgeId(newVal)
        this.bridgeId = newVal
      },
    },
  },
  created() {
    this.getBridgeAll()
    const endTime = moment(new Date()).format('YYYY-MM-DD') + ' 00:00:00'
    const startTime = this.getDay(-2) + ' 00:00:00'
    this.chartTime = [startTime, endTime]
  },
  mounted() {
    this.drawLine([])
    window.addEventListener('resize', () => {
      if (this.line) {
        this.line.resize()
      }
    })
  },
  methods: {
    getLine() {
      console.log('start!')
      // 获取上下限值
      this.$api.mearsuringPointSetting
        .getWarningLine({
          measurePointId: this.id,
        })
        .then((res) => {
          console.log('SXX:', res)
          console.log('上下线值', res.data.data[0][0])
          this.markLine = []
          let data = res.data.data[0][0]
          if (data.firstCap) {
            this.markLine.push({
              silent: false, //鼠标悬停事件  true没有，false有
              lineStyle: {
                //警戒线的样式  ，虚实  颜色
                type: 'dashed',
                color: 'rgba(89, 84, 84, 1)',
                width: 1,
              },
              label: {
                position: 'end',
                formatter: '一级上限' + `(${data.firstCap})`,
              },
              yAxis: data.firstCap, // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
            })
          }
          if (data.firstFloor) {
            this.markLine.push({
              silent: false, //鼠标悬停事件  true没有，false有
              lineStyle: {
                //警戒线的样式  ，虚实  颜色
                type: 'dashed',
                color: 'rgba(89, 84, 84, 1)',
                width: 1,
              },
              label: {
                position: 'end',
                formatter: '一级下限' + `(${data.firstFloor})`,
              },
              yAxis: data.firstFloor, // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
            })
          }

          if (data.secondCap) {
            this.markLine.push({
              silent: false, //鼠标悬停事件  true没有，false有
              lineStyle: {
                //警戒线的样式  ，虚实  颜色
                type: 'dashed',
                color: 'rgba(245, 166, 35, 1)',
                width: 1,
              },
              label: {
                position: 'end',
                formatter: '二级上限' + `(${data.secondCap})`,
              },
              yAxis: data.secondCap, // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
            })
          }
          if (data.secondFloor) {
            this.markLine.push({
              silent: false, //鼠标悬停事件  true没有，false有
              lineStyle: {
                //警戒线的样式  ，虚实  颜色
                type: 'dashed',
                color: 'rgba(245, 166, 35, 1)',
                width: 1,
              },
              label: {
                position: 'end',
                formatter: '二级下限' + `(${data.secondFloor})`,
              },
              yAxis: data.secondFloor, // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
            })
          }

          if (data.thirdCap) {
            this.markLine.push({
              silent: false, //鼠标悬停事件  true没有，false有
              lineStyle: {
                //警戒线的样式  ，虚实  颜色
                type: 'dashed',
                color: 'rgba(220, 81, 81, 1)',
                width: 1,
              },
              label: {
                position: 'end',
                formatter: '三级上限' + `(${data.thirdCap})`,
              },
              yAxis: data.thirdCap, // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
            })
          }

          if (data.thirdFloor) {
            this.markLine.push({
              silent: false, //鼠标悬停事件  true没有，false有
              lineStyle: {
                //警戒线的样式  ，虚实  颜色
                type: 'dashed',
                color: 'rgba(220, 81, 81, 1)',
                width: 1,
              },
              label: {
                position: 'end',
                formatter: '三级下限' + `(${data.thirdFloor})`,
              },
              yAxis: data.thirdFloor, // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
            })
          }
          // this.drawLine(this.data)
        })
    },

    getPoint(data, id) {
      if (data) {
        this.sensorCode = data
        this.id = id
        this.markLine = []
        this.getAngleNum(data)
        if (this.checked) {
          this.getLine()
          this.getAngleLineData(data)
        } else {
          this.getAngleLineData(data)
        }
      }
    },
    getAngleNum(sensorCode) {
      const _params = {
        bridgeId: this.bridgeId,
        // bridgeId:'758335110117326848',
        sensorCode: sensorCode,
        // sensorCode:'ND-03-01',
        beginTime: this.chartTime[0],
        endTime: this.chartTime[1],
      }
      this.$api.analysis.queryAngleNum(_params).then((response) => {
        console.log('最大值最小值是')
        console.log(response)
        if (response.data.success) {
          const _data = response.data.data || {}
          this.max = _data['maxValue'] || 0
          this.min = _data['minValue'] || 0
        }
      })
    },
    getAngleLineData(sensorCode) {
      const _params = {
        bridgeId: this.bridgeId,
        // bridgeId:'758335110117326848',
        sensorCode: sensorCode,
        // sensorCode:'ND-03-01',
        beginTime: this.chartTime[0],
        endTime: this.chartTime[1],
      }
      this.$api.analysis.queryAngleLine(_params).then((response) => {
        console.log('折现图')
        console.log(response)
        if (response.data.success) {
          // YU 修改判断条件，第二做一个提示
          if(response.data.data.length > 0) {
            const _data = response.data.data || []
            let lineData = this.handleArrayfromOneToTwo(_data, 'dateAndTime', 'value')
            console.log(lineData)
            this.drawLine(lineData,sensorCode)
          } else {
            this.drawLine([],sensorCode)
            this.$vs.notify({ text: "数据为空", color: "danger" });
          }
        }
      })
    },
    handleChange(val) {
      if (!this.chartTime) {
        this.$vs.notify({
          text: '请选择时间',
          color: 'danger',
        })
        return false
      }
      if (this.line) {
        this.line.clear()
        this.line.dispose()
      }
      if (this.sensorCode) {
        this.getAngleNum(this.sensorCode)
        this.getAngleLineData(this.sensorCode)
      } else {
        this.$nextTick(() => {
          this.drawLine([])
        })
      }
    },
    drawLine(_seriesData, codeName = '') {
      this.line = new echarts.init(document.getElementById('stressLine'))
      this.line.setOption({
        title: {
          top: '45px',
          left: 'center',
          // text: '倾角趋势分析',
          text: `${codeName}倾角趋势分析`,
          textStyle: {
            align: 'center',
            color: '#699EE5',
            fontSize: 18,
          },
        },
        grid: {
          top: '35%',
          right: '7%',
          left: '5%',
          bottom: '12%',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985',
              fontSize: 12,
            },
          },
          textStyle: {
            fontSize: '100%',
          },
        },
        xAxis: [
          {
            type: 'time',
            min: this.chartTime[0],
            max: this.chartTime[1],
            splitNumber: 14,

            axisLine: {
              show: true,
              lineStyle: {
                color: '#E5E6EB',
              },
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#E5E6EB',
              },
            },
            boundaryGap: false,
            axisLabel: {
              color: '#A7A6AF',
              fontSize: 12,
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '倾角/rad‰',
            max: (value) => {
              if (this.markLine[4]) {
                return this.markLine[4].yAxis
              } else {
                return (value.max).toFixed(2)
              }
            },
            min: (value) => {
              if (this.markLine[5]) {
                return this.markLine[5].yAxis
              } else {
                return (value.min).toFixed(2)
              }
            },
            nameTextStyle: {
              padding: 30,
              color: '#A7A6AF',
              fontSize: 12,
            },
            position: 'left',
            nameLocation: 'middle',
            axisTick: {
              show: false,
            },
            splitNumber: 4,
            splitLine: {
              show: false,
            },
            splitArea: {
              show: true,
              areaStyle: {
                color: ['#F5F6FA', '#fff'],
              },
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#E5E6EB',
              },
            },
            axisLabel: {
              color: '#A7A6AF',
              fontSize: 12,
            },
          },
        ],
        series: [
          {
            data: _seriesData,
            type: 'line',
            symbol: 'none',
            lineStyle: {
              color: '#699EE5',
            },
            itemStyle: {
              color: '#699EE5',
              borderWidth: 1,
            },
            markLine: {
              symbol: 'none',
              label: {
                position: 'middle', //将警示值放在哪个位置，三个值“start”,"middle","end"  开始  中点 结束
              },
              data: this.markLine,
            },
          },
        ],
      })
    },
    getDay(number) {
      let currentDate = new Date(),
        currentTime =
          currentDate.getFullYear() +
          '-' +
          (currentDate.getMonth() + 1 < 10 ? `0${currentDate.getMonth() + 1}` : currentDate.getMonth() + 1) +
          '-' +
          (currentDate.getDate() < 10 ? `0${currentDate.getDate()}` : currentDate.getDate())
      let frontDate = new Date(currentDate)
      frontDate.setDate(currentDate.getDate() + number)
      let frontTime =
        frontDate.getFullYear() +
        '-' +
        (frontDate.getMonth() + 1 < 10 ? `0${frontDate.getMonth() + 1}` : frontDate.getMonth() + 1) +
        '-' +
        (frontDate.getDate() < 10 ? `0${frontDate.getDate()}` : frontDate.getDate())
      return frontTime
    },
    handleArrayfromOneToTwo(_array, m, n) {
      return _array.map((item) => [item[m], item[n]])
    },
    //桥梁选择
    selectBridge() {
      this.$refs.selectBridge.init()
    },
    getData(val) {
      this.bridgeId = val[0].id
      this.editableTabs = val
      this.editableTabsValue = val[0].id
      this.setBridgeId(val[0].id)
    },
    ...mapMutations('angle', {
      setBridgeId: 'BRIDGEID',
    }),
    handleTabClick(tab, event) {
      this.activeTabName = tab.name
    },
    removeTab(id) {
      let tabs = this.editableTabs
      let activeName = this.editableTabsValue
      if (activeName === id) {
        tabs.forEach((tab, index) => {
          if (tab.id === id) {
            let nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.id
            }
          }
        })
      }
      this.editableTabsValue = activeName
      this.editableTabs = tabs.filter((tab) => tab.id !== id)
      this.setBridgeId(this.editableTabsValue)
    },
    getBridgeAll() {
      this.$api.mearsuringPointSetting.getBridgeAll().then((res) => {
        let bridgeListAll = res.data.data[0]
        console.log('res的值', bridgeListAll)
        //let qlId=[];
        let data = JSON.parse(localStorage.getItem('ownInfo'))
        console.log('data的值1111', data[0].code)
        bridgeListAll.map((item, key) => {
          if (item.id == data[0].code) {
            //this.editableTabs = [bridgeListAll[0]];
            this.editableTabs = [item]
            this.editableTabsValue = item.id
            this.setBridgeId(item.id)
          }
        })
      })
    },
  },
}
</script>
<style lang='scss' scoped>
/deep/.el-tabs__item {
  height: 32px;
  line-height: 32px;
  font-size: 12px;
}

/deep/.el-tabs__nav-wrap {
  height: 32px;
}

/deep/.el-tabs--card > .el-tabs__header .el-tabs__item .el-icon-close {
  top: -2px;
}

/deep/.el-tabs--card > .el-tabs__header .el-tabs__item {
  border-bottom: 1px solid #e4e7ed !important;
}

/deep/.is-active.el-tabs__item.is-top.is-active.is-closable {
  background: #327bdc !important;
  color: #fff !important;
}

.alanalysis {
  &-bridge {
    &-card {
      width: 100%;
      height: 300px;
    }

    &-search {
      margin: 20px 0;
    }
  }

  &-chart {
    margin: 20px 0;
    width: 100%;
    height: 430px;
    background: #fff;
    position: relative;

    &-time {
      width: 340px;
      position: absolute;
      right: calc(2% + 10px);
      top: 15px;
      z-index: 999;
    }

    &-box {
      width: 100%;
      height: 100%;
      padding: 20px 10px 10px;
      clear: both;
    }

    &-all {
      width: 100%;
      height: 100%;
    }

    &-info {
      position: absolute;
      top: 20px;
      left: 40px;
      font-size: 12px;
      font-weight: 400;
      color: rgba(153, 153, 153, 1);
    }

    &-left {
      width: 25%;
      height: 100%;
      float: left;
    }

    &-right {
      width: 75%;
      height: 100%;
      float: right;
    }

    &-average {
      width: 50%;
      height: 100%;
      float: left;
    }
  }
}

.search {
  display: flex;
  justify-content: start;
  background: #fff;
  border-radius: 3px;
  height: 32px;

  .seletBtn {
    margin-right: 20px;
    height: 32px;
  }

  .top {
    position: relative;
    top: 6px;
  }
}
</style>
